package com.haredot.controller;

import com.github.pagehelper.Page;
import com.haredot.annotation.DenyStudent;
import com.haredot.annotation.DenyTeacher;
import com.haredot.constraint.SysConst;
import com.haredot.entity.Course;
import com.haredot.entity.Student;
import com.haredot.entity.User;
import com.haredot.service.StudentService;
import com.haredot.vo.LayuiPage;
import com.haredot.vo.LayuiPageResultVo;
import com.haredot.vo.R;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping("/student")
public class StudentController {

    @Resource
    private StudentService studentService ;
    /**
     * 学生信息展示页面
     * @return
     */
    @GetMapping("/infos")
    public String infos() {
        return "student" ;
    }

    @GetMapping("/add")
    public String addPage() {
        return "studentAdd" ;
    }

    @GetMapping("/course")
    public String course() {
        return "courseTransfer" ;
    }

    @GetMapping("/mark")
    public String mark() {
        return "studentMark" ;
    }

    /**
     * 添加学生
     * @param student
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    @DenyStudent
    public R<Student> addStudent(@RequestBody @Valid Student student) {
        return studentService.save(student);
    }

    @GetMapping("/list")
    @ResponseBody
    public LayuiPageResultVo<Student> list(@RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
                                           @RequestParam(value = "limit", defaultValue = "10", required = false)Integer limit,
                                           @RequestParam(value = "sno", required = false) Long sno,
                                           HttpSession session) {
        // 获取当前登录的用户
        User user = (User)session.getAttribute(SysConst.CURRENT_USER);
        LayuiPage layuiPage = new LayuiPage(page, limit);

        R<Page<Student>> ret = studentService.queryStudentList(layuiPage, sno, user);
        return LayuiPageResultVo.convertR(ret);
    }

    /**
     * 跳转到修改学生页面
     * @param sno
     * @return
     */
    @GetMapping("/modify/{sno}")
    public String modifyPage(@PathVariable("sno") Long sno, ModelMap modelMap) {
        // 根据 sno 查询学生信息、
        R<Student> ret = studentService.queryStudentById(sno);

        if (ret.getStatus()) {
            modelMap.addAttribute("student", ret.getData());
        }
        return "studentModify" ;
    }

    @PostMapping("/modify/{sno}")
    @ResponseBody
    public R<Student> modifyStudent(@PathVariable("sno") Long sno, @RequestBody Student student) {

        if (!Objects.equals(student.getId(), sno)) {
            return R.<Student>fail(R.StatusCode.BAD).data(Map.of("id", "参数错误"));
        }

        return studentService.modify(student);
    }

    @DeleteMapping("/remove/{sno}")
    @ResponseBody
    @DenyStudent
    public R<?> deleteStudent(@PathVariable("sno") Long sno){

        return studentService.remove(sno);
    }

    @DeleteMapping("/batch/remove")
    @ResponseBody
    @DenyStudent
    public R<?> removeBatch(@RequestBody List<Long> ids){
        if (ids.isEmpty()) {
            return R.fail(R.StatusCode.BAD).build();
        }
        return studentService.batchRemove(ids);
    }
    /**
     * 查询学生选课情况 （穿梭框使用）
     */
    @GetMapping("/course/list")
    @ResponseBody
    public R<Course> queryCourseList(@RequestParam("sno") Long sno) {

        return studentService.queryCourseListBySno(sno);
    }

    @PutMapping("/course/bind{sno}")
    @ResponseBody
    public R<?> bindCourse(@PathVariable("sno") Long sno, @RequestBody List<Integer> courseIds) {

        return studentService.bindCourse(sno, courseIds);
    }

    /**
     * 查询当前登录学生的成绩信息 (禁止教师使用)
     * @return
     */
    @GetMapping("/mycourse")
    @ResponseBody
    @DenyTeacher
    public LayuiPageResultVo<Map<String, Object>> queryStudentCourse(HttpSession session) {
        // 获取当前登录的用户信息
        User user = (User)session.getAttribute(SysConst.CURRENT_USER);
        // 查询该用户的各学科成绩
        List<Map<String, Object>> list =studentService.queryCourseListByCurrentStudent(user.getUsername());

        LayuiPageResultVo<Map<String, Object>> ret = new LayuiPageResultVo<>() ;

        ret.setCode(0);
        ret.setData(list);

        // 设置合并行信息
        Map<String, Integer> totalRow = list.stream().reduce(new HashMap<>(), (map, data)-> {
            Integer mark = Integer.valueOf(String.valueOf(data.get("mark")));
            Integer credit = Integer.valueOf(String.valueOf(data.get("credit")));
            if (map.isEmpty()) {
                map.put("mark", mark);
                map.put("credit", credit);
            }else{
                Integer newMark = map.get("mark") + mark ;
                Integer newCredit = map.get("credit") + credit ;
                map.put("mark", newMark);
                map.put("credit", newCredit);
            }
            return map ;
        }, (a, b)-> a) ;

        ret.setTotalRow(totalRow);

        return ret ;
    }
}
